//=============================================================================
// System  : MatchKit
// File    : MatchableClassInfo.cs
// Author  : Fabio Bussu  (matchkit@fabiobussu.it)
// Updated : 04/16/2013
// Note    : Copyright 2013, Fabio Bussu, All rights reserved
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code.  It can also be found
// at the project website: http://matchkit.codeplex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version     Date     Who  Comments
// ============================================================================
// 1.0.0.0  04/16/2013   FB  First draft
//=============================================================================
using System;
using System.Collections.Generic;
using System.Reflection;

namespace MatchKit.ObjectMapping
{
	sealed class MatchableClassInfo
	{
		private static Dictionary<Type, MatchableClassInfo> _cache = new Dictionary<Type, MatchableClassInfo>();

		public static MatchableClassInfo Get(Type type)
		{
			if (type == null)
				throw new ArgumentNullException("type", "type cannot be null");
			MatchableClassInfo v;
			lock (_cache)
			{
				if (!_cache.TryGetValue(type, out v))
				{
					_cache[type] = v = InternalCreate(type);
				}
			}
			return v;
		}

		private static MatchableClassInfo InternalCreate(Type type)
		{
			var matchableClassAttribute = ReflectionUtils.GetAttribute<MatchableClassAttribute>(type);
			if (matchableClassAttribute == null)
				throw new MatchKitMappingException(2, "Type [{0}] must be marked with MatchableClassAttribute", type.FullName);
			if (!ReflectionUtils.IsAllocable(type))
				throw new MatchKitMappingException(3, "Type [{0}] must be an allocable type with a default constructor (even private)", type.FullName);
			var hasMappingEvents = typeof(IMatchMappingEvents).IsAssignableFrom(type);
			var members = new List<MatchableMemberInfo>();
			foreach (var member in EnumEligibleMembers(type))
				members.Add(new MatchableMemberInfo(new FieldOrProperty(member)));
			if (members.Count == 0)
				throw new MatchKitMappingException(4, "Type [{0}] is marked as MatchableClass but does not contains any matchable members", type.FullName);
			return new MatchableClassInfo(type, members.ToArray(), hasMappingEvents);
		}

		private static IEnumerable<MemberInfo> EnumEligibleMembers(Type type)
		{
			var bflags = BindingFlags.Instance | BindingFlags.Static
				| BindingFlags.NonPublic | BindingFlags.Public
				| BindingFlags.FlattenHierarchy;

			var temp = new List<MemberInfo>();

			foreach (var m in type.GetMembers(bflags))
			{
				if ((m is FieldInfo || m is PropertyInfo)
					&& ReflectionUtils.GetAttribute<MatchableMemberAttribute>(m) != null)
					temp.Add(m);
			}

			temp.Sort((a, b) => ReflectionUtils.GetAttribute<MatchableMemberAttribute>(a).Position
				.CompareTo(ReflectionUtils.GetAttribute<MatchableMemberAttribute>(b).Position));

			return temp;
		}

		public Type Type;
		public MatchableMemberInfo[] Members;
		public bool HasMappingEvents;
		public MatchableMemberInfo SeparatorElement;
		public bool HasPointOfNoReturn;

		private MatchableClassInfo(Type type, MatchableMemberInfo[] members, bool hasMappingEvents)
		{
			Type = type;
			HasMappingEvents = hasMappingEvents;
			Members = members;
			CheckForSeparator();
			CheckForPointOfNoReturn();
		}

		private void CheckForSeparator()
		{
			for (int i = 0; i < Members.Length; i++)
			{
				var member = Members[i];

				if (member.IsSeparatorElement)
				{
					if (i < Members.Length - 1)
						throw new MatchKitMappingException(5, "The separator element for type [{0}] must be the last matchable member", Type.FullName);

					SeparatorElement = member;
				}
			}
		}

		private void CheckForPointOfNoReturn()
		{
			for (int i = 0; i < Members.Length; i++)
			{
				var member = Members[i];

				if (member.IsPointOfNoReturn)
				{
					if (HasPointOfNoReturn)
						throw new MatchKitMappingException(24, "The type [{0}] contains more than one point of no return", Type.FullName);

					HasPointOfNoReturn = true;
				}
			}
		}
	}
}
